package Offer.offer2019;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

/**
 * 单例模式 方法三 饿汉式
 *
 * @author: leiwenkang02@meituan.com
 * @date: 2019/4/14
 * @time: 18:20
 */
public class Offer02b {

    //定义一个私有的静态实例
    private static Offer02b instance = new Offer02b();

    //1.私有的构造方法，保证不能通过外部new出实例
    private Offer02b() {

    }

    //2.获取单例  因为构造方法私有了，只能通过static静态方法获取到实例
    public static Offer02b getSingleInstance() {
        return instance;
    }

    //测试
    public static void main(String[] args) {

        Set<Offer02b> set = new HashSet<>();
        //单线程
//        for (int i = 0; i < 10; i++) {
//            Offer02 offer02 = Offer02.getSingleInstance();
//            set.add(offer02);
//            System.out.println(offer02);
//        }
        //开启10个线程线程
        int threadCount = 10;
        CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            new Thread(() -> {
                Offer02b offer02 = Offer02b.getSingleInstance();
                set.add(offer02);
                System.out.println("线程" + Thread.currentThread().getName() + "的结果返回为 : " + offer02);
                countDownLatch.countDown();
            }).start();
        }
        try {
            countDownLatch.await();
        } catch (Exception e) {
            System.out.println("等待线程执行异常");
        }
        System.out.println("等待线程执行完毕！");
        System.out.println(set.size());
    }

}
